import {
	Inject
} from 'plugins'
import config from 'config';

@Inject('$scope', '$state', 'ui.dialog', 'ui.http', 'ui.api')
export class ApiLayout {
	constructor($scope, $state, dialog, http, api) {
		api.tree({
			scope: $scope,
			type: 'tree',
			url: 'tree.php',
			params: {

			}
		});

		$scope.treeReload = function() {
			api.treeReload.apply($scope, arguments);
		}

		var getTreeNode = $scope.getTreeNode = function() {
			return $scope.selectedTreeNode;
		}

		$scope.hasNodeSelected = function() {
			var node = getTreeNode();
			return node != null;
		}

		// 接口类型
		var _type = 'api';
		$scope.isApiNode = function() {
			var node = getTreeNode(),
				root;
			return !node || _type == node.type;
		}

		$scope.changeNode = function(node) {
			$scope.selectedTreeNode = node;

			$scope.$parent.select($scope.$parent.activeIndex);
		}

		$scope.add = function() {
			var node = getTreeNode();
			var id, type;
			if (node) {
				id = node.id;
				type = node.type;
			}
			
			return api.form({
				title: '新建分类', 
				template: require('../views/form.tpl.html'),
				name: 'api_add',
				data: {
					id: id
				}
			}).then(function() {
				treeReload();
			});
		}
		$scope.edit = function() {
			var node = getTreeNode();
			var id = node.id;
			
			return api.form({
				title: '编辑分类', 
				template: require('../views/form.tpl.html'), 
				name: 'api_edit',
				resolveWait: http.post({
						name: 'api_edit_item',
						params: {
							id: id
						}
					})
			}).then(function() {
				treeReload();
			});
		}
		$scope.remove = function() {
			var node = getTreeNode();
			var id = node.id;
			var type = node.type;

			dialog.confirm('确定要删除当前' + (type == _type ? '接口' : '分类') + '？').result.then(function(r) {
				if (r) {
					http.post({
						name: 'api_remove',
						params: {
							id: id
						},
						success: function() {
							treeReload();
						}
					})
				}
			});
		}
	}
}